package com.thirteen.app.controller;

import com.thirteen.app.dto.ExamRecordId;
import com.thirteen.app.dto.PaperRespose.AnswerDto;
import com.thirteen.app.dto.PaperRespose.PaperDto;
import com.thirteen.app.service.ExamRecordService;
import com.thirteen.app.service.ExamService;
import com.thirteen.app.service.JudgeService;
import com.thirteen.app.service.PaperService;
import com.thirteen.app.utils.tools.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags = {"试卷"})
@RestController
@RequestMapping("/api/student/paper")
@CrossOrigin
public class PaperController {

    @Resource
    private PaperService paperService;

    @Resource
    private ExamRecordService examRecordService;

    @Resource
    private ExamService examService;

    @Resource
    private JudgeService judgeService;

    @ApiOperation("开始考试")
    @GetMapping("startExam")
    public CommonResult startExam(Integer examId, Integer userId) {

        Integer examRecordId = null;

        try {

            if (!examRecordService.canOpenNewExam(examId, userId)) {
                return CommonResult.failed("请完成当前进行的考试");
            }
            if (!examRecordService.isFirstAttend(examId, userId)) {
                if (!examRecordService.canRedoExam(examId, userId)) {
                    return CommonResult.failed("该考试的次数已用完");
                }
            }
            examRecordId = examService.startExam(examId, userId);
            if (examRecordId < 0) {
                return CommonResult.failed("非法操作");
            }
        } catch (Exception e) {
            return CommonResult.failed("非法操作");
        }
        PaperDto paperDto;
        try {
            paperDto = paperService.queryPaper(examRecordId);
        } catch (Exception e) {
            return CommonResult.failed("获取试卷失败");
        }
        return CommonResult.success(paperDto);
    }

    @ApiOperation("提交试题答案")
    @PostMapping("commitQu")
    public CommonResult submitQuestion(@RequestBody AnswerDto answerDto) {
        paperService.submitAnswer(answerDto);
        return CommonResult.success("success");
    }

    @ApiOperation("提交试卷")
    @PostMapping("commitPaper")
    public CommonResult submitPaper(@RequestBody ExamRecordId eId) {
        Integer examRecordId = Integer.parseInt(eId.getExamRecordId());

        if (!paperService.submitPaper(examRecordId)) {
            return CommonResult.failed("提交试卷失败");
        }

//        if (paperService.isMachineJudge(examRecordId) == true) {
//            judgeService.judgeByMachine(examRecordId);
//        }

        return CommonResult.success("提交试卷成功");
    }


}
